package com.chenjj.java.map.linkedhashmap;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class LRU {
    public LinkedHashMap<String,String> cacheMap;

    public int capacity = 5;

    public LRU(){
        cacheMap = new LinkedHashMap(capacity, 1.0f,true){
            @Override
            protected boolean removeEldestEntry(Map.Entry entry) {
                return size() > capacity;
            }
        };
        System.out.println(cacheMap.size());
    }

    public synchronized void put(String key,String value){
        cacheMap.put(key,value);
    }

    public void printCache(){

        //这样写会有 ConcurrentModificationException，因为在执行cacheMap.get(key)的时候会modCount++（因为accessOrder=true）
//        Iterator<String> it = cacheMap.keySet().iterator();
//        while (it.hasNext()){
//            String key = it.next();
//            String value = cacheMap.get(key);
//            System.out.println("key="+key+",value="+value);
//        }

        //这样写不会
        Iterator entyIt = cacheMap.entrySet().iterator();
        while (entyIt.hasNext()){
            Map.Entry entry = (Map.Entry) entyIt.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            System.out.println("key="+key+",value="+value);
        }
    }
}
